<template>
  <Container class="single-sale">
    <div class="container-header title title-center" slot="header">单品促销</div>
    <div class="bg-light">
      <div class="container-title">
        <span>促销规则</span>
        <Button type="primary" @click="onEditRule">修改促销</Button>
      </div>
      <Form :label-width="100" ref="form" >
        <Row>
          <Col span="8">
            <FormItem label="促销名称：">{{$store.state.singleSale.form.name}}</FormItem>
            <FormItem label="促销对象：">{{singleGrade}}</FormItem>
            <FormItem label="促销备注：">{{$store.state.singleSale.form.remarks}}</FormItem>
          </Col>
          <Col span="8">
            <FormItem label="显示标签：">{{singleType}}</FormItem>
            <FormItem label="限购数量：">
              <div v-show="singleNum">不限制购买数量</div>
              <div v-show="!singleNum"><span>sku最少{{$store.state.singleSale.form.least}}</span> , <span>sku最多{{$store.state.singleSale.form.max}}</span></div>
            </FormItem>
             <FormItem label="宣传语：">{{$store.state.singleSale.form.slogan}}</FormItem>
          </Col>
          <Col span="8">
            <FormItem label="促销时间：">{{$store.state.singleSale.form.date[0] | dateTime }} - {{$store.state.singleSale.form.date[1] | dateTime}}</FormItem>
            <FormItem label="参加商品：">部分商品参加</FormItem>
          </Col> 
        </Row>
      </Form>
    </div>
    <div class="bg-light mt">
        <div class="container-header">
            <SearchSale  @onSearchData="onSearchData"></SearchSale>
        </div>
        <Tabs v-model="tab">
          <template slot="extra">
            <template v-if="tab === 'tab1'">
              <Form :label-width="100" ref="setForm" :model="setForm" inline class="item">
                <FormItem>
                  <RadioGroup v-model="setForm.type">
                    <Radio label="1">打 <InputNumber v-model="setForm.discountNum" :min="0" :max="999"></InputNumber> 折</Radio>
                    <Radio label="2">减 <InputNumber v-model="setForm.subNum" :min="0" :max="999"></InputNumber> 元</Radio>
                    <Radio label="3">促销 <InputNumber v-model="setForm.saleNum" :min="0" :max="999"></InputNumber> 元</Radio>
                  </RadioGroup>
                </FormItem>
                <Button  @click="onSetbatch">批量设置</Button>
              </Form>
              <Button class="item" type="primary" icon="md-add" @click="onJoinAdd">批量加入</Button>
            </template>
            <Button v-if="tab === 'tab2'" class="item" type="primary" icon="md-add" @click="onJoinDelete">批量撤出</Button>
          </template>
          <TabPane label="选择主商品" name="tab1">
            <choiceCommidy  ref="choiceCommidy" ></choiceCommidy>
          </TabPane>
          <TabPane :label="label1" name="tab2">
              <mainCommidy  ref="mainCommidy" ></mainCommidy>
          </TabPane>
        </Tabs>
      </div>
      <div class="container-footer bg-white" slot="footer">
        <Button size="large"  @click="jumpPrevPage">返回</Button>
        <Button type="primary" size="large" class="ml" :loading="loading" @click="onPrevertion">保存</Button>
      </div>
  </Container>
</template>
<script>
import SearchSale from '@/views/sales/common/SearchSale'
import Treeselect from '@riophae/vue-treeselect';
import choiceCommidy from "./list/ChoiceCommidyItem";
import mainCommidy from "./list/MainCommidyItem";
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
import {columns1, columns2, setSelectList, setCascaderList, formatDate, getPuduct} from "./list/SingleMethods.js";
import {onSet} from "@/views/sales/common/TableSaleMethods";
import {mapGetters} from "vuex"
export default {
  components: {
    Treeselect,
    mainCommidy,
    choiceCommidy,
    SearchSale
  },
  data() {
    return {
      id: this.$route.query.id || '',
      type: this.$route.query.type || '',
      isSave: true,
      loading: false,
      tab: 'tab1',
      options: [],
      brandList: [],
      searchForm: {
          brandId: '',
          categoryId: [],
          keyword: '',
          code: '',
          skuCode: ''
      },
      setForm: {
        type: '1',
        discountNum: 9,
        subNum: 0,
        saleNum: 0
      },
      label1: (h) => {
        return h('div', [
          h('span', '已选主商品'),
          h('Badge',{
            props: {
              count: this.getSaleNum
            }
          })
        ])
      }
    }
  },
  mounted() {
    /*
      1. 如果有值并且有id的情况---不刷新
    */
    (this.id && !this.$store.state.singleSale.GetsaleData.length) && this.getData()
  },
  methods: {
    getData() {
      this.$ajaxGet(`/activity/activity_sku_list/${this.id}`).then(data => {
        this.$store.state.singleSale.GetsaleData = (data || []).map(item => {
          return {
            id: item.item[0].productId,
            checked: false,
            buttonChecked: false,
            showChildren: false,
            discount: '',
            reduce: '',
            sale: '',
            limitQuantity: '',
            code: item.productSn,
            salePrice: '',
            reduce: '',
            stock: '',
            isShelf: item.isShelf,
            discount: '',
            title: item.title,
            sellOutQuantity: '',
            quantity: item.quantity,
            productSkuList: item.item.map(todo => {
              return {
                id: todo.skuId,
                productId: todo.productId,
                productSn: todo.productSn,
                parentcode: item.productSn,
                checked: false,
                buttonChecked: false,
                showChildren: false,
                discount: '',
                reduce: '',
                sale: '',
                limitQuantity: todo.limitQuantity,
                code: todo.skuSn,
                salePrice: todo.productSkuInfo.salePrice,
                reduce: '',
                sale: todo.promotionPrice,
                stock: '',
                isShelf: todo.isShelf,
                discount: '',
                title: '',
                stock: todo.productSkuInfo.stock,
                returnPrice: '',
                quantity: item.quantity,
                sellOutQuantity: todo.sellOutQuantity
              }
            })
          }
        })
        this.setItem(this.$store.state.singleSale.GetsaleData, ['sale', 'limitQuantity', 'sellOutQuantity'])
        this.onSearchData()
      })
    },
    setItem(data, num) {
      for (let item of data) {
        for (let todo of item.productSkuList) {
          for(let type of num) {
            onSet(todo, item, type)
          }
        }
      }
    },
    onSearchData (param) {
      this.$refs.choiceCommidy.getProductData(param)
    },
    jumpPrevPage() {
      this.$router.back();
    },
    isSixDiscount(data) {
      let status = false
      for (let item of data) {
        for (let todo of item['productSkuList']){
          if(todo['sale']/todo['salePrice']<0.6) {
            status = true
          }
        }
      }
      return status      
    },
    isPriceEmpty (data, type) {
      let status = false
      for (let item of data) {
        for (let todo of item['productSkuList']){
            if(!todo[type]) {
                status = true
            }
        }
      }
      return status
    },
    onPrevertion () {
      if (!this.$store.state.singleSale.form.name ){
        this.$Message.error("请填写完整促销规则")
        return false
      }
      if(this.isPriceEmpty(this.$store.state.singleSale.GetsaleData, 'sale')) {
        this.$Message.error("促销价格不能为空")
        return false
      }
      if(this.isPriceEmpty(this.$store.state.singleSale.GetsaleData, 'sellOutQuantity') && this.isShowDrop) {
        this.$Message.error("促销库存不能为空")
        return false
      }
      if(this.isSixDiscount(this.$store.state.singleSale.GetsaleData)) {
        this.$Message.error("促销价格必须大于6折")
        return false
      }
      let url = "/activity/single/save"
      if (this.id && this.type) url = '/activity/single/edit'
      let params = {
        activityInfoDTO: {
          activityDescription: this.$store.state.singleSale.form.remarks, //活动备注
          activityName: this.$store.state.singleSale.form.name, //促销名称
          joinTypeEnum: 'PART', //参与方式
          productSkuList: this.productSkuList, //已选商品列表,
          storeTypeEnumList: this.promotionMemberScope, //活动对象
          startDate: this.timeList[0].startDatetime,
          endDate: this.timeList[0].endDatetime,
          shelfStatusEnum: 'ON'
        },
        activitySingleDTO: {
          advertisingSlogan: this.$store.state.singleSale.form.slogan, //宣传语
          isLimitOneOrder: this.isLimitOneOrder,//限购一单
          isLimitQuantity: this.isLimitQuantity, //是否限购数量
          limitMax: this.limitMax, //最大值
          limitMin: this.limitMin, //最小值
          limitOneOrderTypeEnum: this.limitOneOrderTypeEnum, //限账号
          singlePromotionTypeEnum: this.singlePromotionTypeEnum //促销类型
        }
      }
      let self = this;
      this.loading = true;
      if (this.id && this.type) params.activitySingleDTO.activityId = this.id
      this.$jsonPost(url,params).then((data) => {
        self.$Message.success((this.id && this.type) ? "编辑活动成功" : "新增活动成功")
        self.$store.commit('setSingleSaleEmpty')
        self.$router.push({name: 'sales/list'})
        this.loading = false
      }).catch((data)=>{
        this.loading = false
      })
    },
    onSetbatch () {
      let object = {}
      if (this.setForm.type == 1) {
        object = {index: 1, val: this.setForm.discountNum}
      }else if (this.setForm.type == 2) {
        object = {index: 2, val: this.setForm.subNum}
      }else if (this.setForm.type == 3) {
        object= {index: 3, val: this.setForm.saleNum}
      }
      this.$refs.choiceCommidy.onSetbatch(object)
    },
    onEditRule() {
      this.$Modal.confirm({
        title: '温馨提示',
        content: '您确定要修改活动吗？修改活动当前页面不保存',
        onOk: ()=> {
          this.$router.back()
        }
      })
    },
    onJoinAdd() {
      this.$refs.choiceCommidy.getSaleData("checked")
    },
    onJoinDelete() {
      this.$refs.mainCommidy.deleteSaleData()
    },
  },
  computed: {
    ...mapGetters([
      'isShowDrop'
    ]),
    getSaleNum () {
      return this.$store.getters.getSingleSaleNum
    },
    singleGrade () {
      return this.$store.getters.singleGrade;
    },
    singleType () {
      return this.$store.getters.singleType
    },
    singleNum () {
      return this.$store.getters.singleNum
    },
    productSkuList () {
      let getParam = ["productId", "id", "code",'sale',"parentcode"]
      if (this.$store.state.singleSale.form.type == '1') {
        getParam.push("limitQuantity")
      } else {
        getParam.push("sellOutQuantity")
      }
      return getPuduct(this.$store.state.singleSale.GetsaleData, {child: "productSkuList", getParam: getParam})
    },
    timeList() {
      return [{
        startDatetime: formatDate(this.$store.state.singleSale.form.date[0],true),
        endDatetime: formatDate(this.$store.state.singleSale.form.date[1],true)
      }]
    },
    promotionMemberScope() {
      return this.$store.state.singleSale.form.grade;
    },
    singlePromotionTypeEnum () {
      return this.$store.getters.singleSaleType
    },
    limitMax () {
      return this.$store.getters.singlelimitMax
    },
    limitMin () {
      return this.$store.getters.singlelimitLeast
    },
    isLimitQuantity () {
      return this.$store.getters.singleLimitQuantity
    },
    isLimitOneOrder () {
      return this.$store.getters.singleLimitOneOrder
    },
    limitOneOrderTypeEnum () {
      return this.$store.getters.singletOneOrderTypeEnum
    }
  }
}
</script>

